package net.neptech.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import net.neptech.exception.BusinessException;
import net.neptech.mapper.UserMapper;
import net.neptech.model.sys.User;
import net.neptech.service.UserService;
import net.neptech.utils.SecurityUtils;
import net.neptech.utils.StringUtils;
import net.neptech.vm.constant.UserConstants;
import net.neptech.vm.enums.ResultStatusEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @Author: liyuxiang
 * @Date: 2025/8/17 21:02
 * @Description: TODO
 */
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    UserMapper userMapper;

    @Override
    @Transactional
    public void registerUser(User user) {
        // 用户名或密码为空 错误
        if (StringUtils.isAnyBlank(user.getUsername(), user.getPassword())) {
            throw new BusinessException(ResultStatusEnum.BAD_REQUEST.getCode(), "用户/密码必须填写");
        }
        if (user.getUsername().length() < UserConstants.USERNAME_MIN_LENGTH
                || user.getUsername().length() > UserConstants.USERNAME_MAX_LENGTH) {
            throw new BusinessException(ResultStatusEnum.BAD_REQUEST.getCode(), "账户长度必须在2到20个字符之间");
        }
        if (user.getPassword().length() < UserConstants.PASSWORD_MIN_LENGTH
                || user.getPassword().length() > UserConstants.PASSWORD_MAX_LENGTH) {
            throw new BusinessException(ResultStatusEnum.BAD_REQUEST.getCode(), "密码长度必须在5到20个字符之间");
        }
        //校验用户名是否存在
        User existsUserName = userMapper.selectOne(new LambdaQueryWrapper<>(User.class).eq(User::getUsername, user.getUsername()));
        if (existsUserName != null) {
            throw new BusinessException(ResultStatusEnum.USERNAME_ALREADY_EXISTS);
        }
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        userMapper.insert(user);
    }

    @Override
    public User selectUser(User user) {

        //根据多条件判断，用户名、openid
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank(user.getUsername())) {
            queryWrapper.eq(User::getUsername, user.getUsername());
        }
        //根据
        if (StringUtils.isNotBlank(user.getOpenId())) {
            queryWrapper.eq(User::getOpenId, user.getOpenId());
        }
        user = userMapper.selectOne(queryWrapper);
        return user;
    }
}
